import { createDts } from './create-boot'

function transfer2Dts(env: Record<string, string>, coma?: Record<string, string[]>) {
  let str = '{'
  let len = 0
  for (const key in env) {
    len++
    if (coma?.[key]?.length) {
      str += `\n  /** @desc ${coma[key].join('').replace(/^\s+|\s+$/g, '') || ''}*/`
    }
    str += `\n  ${key}: ${typeof env[key]}`
  }
  return len > 0 ? `${str}\n}` : 'Record<string, string>'
}
export function getDeclaration({ root, env, localEnv, envComa, localEnvComaMap }: Record<string, any>) {
  const envDts = transfer2Dts(env, envComa)
  const localEnvDts = transfer2Dts(localEnv, localEnvComaMap)

  const code
    = `// types/mui-env.d.ts
declare const __APP_ENV__: ${envDts};
declare const __APP_LOCAL_ENV__: ${localEnvDts};
declare const __APP_BOOT_CONFIG__: BootEnvConfig;

declare module 'virtual:mui-env' {
  export const env: ${envDts};
  export const localEnv: ${localEnvDts};
  export const bootConfig: BootEnvConfig;
}

interface BootEnvConfig {
  plat: string;
  rawPlat: string;
  isDev: boolean;
  nodeEnv: 'development' | 'production';
  proxyUrl: string;
  envName: string;
}

// types/mui-proxy-map.d.ts
declare module 'virtual:mui-proxy-map' {
  const proxyMap: Record<string, string>;
  export { proxyMap };
}
`
  createDts(root, code, '')
}
